<?php
namespace app\home\logic;

use think\Model;

class BorrowCount extends Model {
    static function UpdateBorrowCount($data = []) {
        if (!isset($data['user_id'])) {
            return null;
        }
        $user_id = $data['user_id'];
        $result = db('borrow_count')->where(['user_id' => $data['user_id']])->find();
        if (!$result) {
            db('borrow_count')->insert(['user_id' => $data['user_id']]);
        }
        $result = db('borrow_count_log')->where(['nid' => $data['nid']])->find();
        if ($result) {
            return null;
        }
        $prefix = config('database.prefix');
        $remark = serialize($data);
        $sql = "insert into `{$prefix}borrow_count_log` set user_id={$data['user_id']},borrow_nid='{$data['borrow_nid']}',nid='{$data['nid']}',remark='{$remark}',addtime='".time()."'";
        $ex = db()->execute($sql);
        if (!$ex) {
            return null;
        }
        unset($data['nid']);
        unset($data['borrow_nid']);

        $sql = "update `{$prefix}borrow_count` set user_id='{$data['user_id']}'";
        unset ($data['user_id']);
        foreach ($data as $key => $value){
            $sql .= ",`{$key}`=`{$key}`+{$value}";
        }
        $sql .= " where user_id='{$user_id}'";
        $ex = db()->execute($sql);
        if (!$ex) {
            return null;
        }
        return true;
    }
}